<?
class PostItemForm extends Form{
	var $max_image_page=1,$images_per_page=9,$no_image='style/images/no-images-69x53.jpg';
	var $item_images=array(),$img_url='',$jsImages = array(),$browser_is_ie = 0;
	
	function __construct()
	{
		//check secrurity
		if(!$_SERVER["HTTP_ACCEPT_ENCODING"] && !$_SERVER["HTTP_ACCEPT_LANGUAGE"]){
			Url::redirect('home');
		}
					
		Form::Form('PostItemForm');		
		AZLib::getCats();
		
		CGlobal::$website_title='Đăng sản phẩm';

		$this->link_css('style/postItem.css');
			
		$this->link_css('style/gallery.css');

		//$this->link_js('javascript/jquery/jquery-1.3.2.js');
		$this->link_js('javascript/jquery/jquery.livequery.js');
		$this->link_js('javascript/jquery/jquery.jcache.js');
		$this->link_js('javascript/jquery/jquery.form.js');
		$this->link_js('javascript/jquery/jquery.ui.js');
		$this->link_js('javascript/jquery/ui.draggable.js');
		$this->link_js('javascript/jquery/ui.droppable.js');
		
		// For checking flash version of browser
		$this->link_js('javascript/AC_RunActiveContent.js');
		
		// For ajax upload when use IE or other browser has no flash
		$this->link_js('javascript/si.files.js');
		$this->link_js('javascript/ajaxfileupload.js');
		
		// For flash upload
		$this->link_js('javascript/swfupload/swfupload.js');
		$this->link_js('javascript/swfupload/js/swfupload.swfobject.js');
		$this->link_js('javascript/swfupload/js/swfupload.queue.js');
		$this->link_js('javascript/swfupload/js/fileprogress.js');
		$this->link_js('javascript/post_item_handlers.js');

		if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
		{
			$this->browser_is_ie = 1;
		}
		else
		{
			
			$this->browser_is_ie = 0;
		}
		$this->link_js('javascript/jquery/jquery.event.drag-1.0.js');
		$this->link_js('javascript/post_item.js');
		
		if((int)ini_get("memory_limit")<64){@ini_set("memory_limit","64M");}
		
		//$this->no_image = AZLib::getImageSrc('',70,70);
		$this->no_image = STATIC_URL.'style/images/no-images-69x53.jpg';
		
		$index=1;
		for($i=1;$i<=$this->max_image_page;$i++){//trang ảnh
			$this->item_images[$i]=array();

			for($n=1; $n<=$this->images_per_page;$n++){//số ảnh trên trang
				$this->item_images[$i][$n]['stt']=$index;
				if(isset($_POST['img_new'][$index]) && $_POST['img_new'][$index]){
					//$this->item_images[$i][$n]['image_url']	=AZLib::getImageThumb($_POST['image_url'][$index],80,80);
					//$this->item_images[$i][$n]['image_url']	= $this->no_image;
					
					$this->jsImages[$index]['w180'] = 'thumb_w/180/';
					$this->jsImages[$index]['img_server'] = $_POST['i_server'][$index];
					//$this->jsImages[$index]['server_address'] = CGlobal::$img_server[$_POST['i_server'][$index]];
					$this->jsImages[$index]['img_url'] = $_POST['i_url'][$index];
					$this->jsImages[$index]['image_url'] = AZLib::getImageThumb($_POST['i_url'][$index],80,80,0,$_POST['i_server'][$index]);
					
					$this->item_images[$i][$n]['img_server']=	$_POST['i_server'][$index];
					$this->item_images[$i][$n]['i_url'] = 	$_POST['i_url'][$index];
					$this->item_images[$i][$n]['image_url'] = AZLib::getImageThumb($_POST['i_url'][$index],80,80,0,$_POST['i_server'][$index]);
					$this->item_images[$i][$n]['title']		=   $_POST['image_title'][$index];
					$this->item_images[$i][$n]['id']		=   '0';
					$this->item_images[$i][$n]['img_new_id']	=$_POST['img_new'][$index];
					$this->item_images[$i][$n]['have_img']		=1;
					$this->item_images[$i][$n]['img_del_id']	=0;
				}
				else{
					$this->item_images[$i][$n]['img_server']=	0;
					$this->item_images[$i][$n]['image_url']	=	$this->no_image;
					$this->item_images[$i][$n]['i_url'] = 	'';
					$this->item_images[$i][$n]['title']		='Ghi chú ảnh';
					$this->item_images[$i][$n]['id']		='';
					$this->item_images[$i][$n]['img_new_id']	=0;
					$this->item_images[$i][$n]['have_img']		=0;
					$this->item_images[$i][$n]['img_del_id']	=0;
				}
				$index++;
			}
		}
		
		AZLib::getFilters();
	}
	
	function draw(){	
		global $display;
		
		//For ajax_upload form
		$display->add('url_gallery',WEB_ROOT.AZRewrite::formatUrl('?page=gallery&is_popup=1&user_id='.User::id()));	
		//$display->add('no_img_upload',AZLib::getImageSrc('',100,100));
		$display->add('no_img_upload',$this->no_image);
		
		// Keep item avatar when update false
		if(isset($_POST["avatar_img_server"])&&$_POST["avatar_img_server"])
		{
			$avatar['img_server'] = $_POST["avatar_img_server"];
			$avatar['img_url'] = $_POST["avatar_img_url"];
			$avatar['thumb280_280'] = AZLib::getImageThumb($_POST["avatar_img_url"],280,280,0,$_POST["avatar_img_server"]);
			$avatar['max_path']		= AZLib::getImageThumbMax($_POST["avatar_img_url"],'thumb_max',1,$_POST["avatar_img_server"]);
			$display->add('avatarInfo',$avatar);
			$display->add('avatar',json_encode($avatar));
		}

        $display->add('item_user_id', User::id());
        $display->add('user_name', User::user_name());
        
		$display->add('user_id',		User::id());
		$display->add('is_can_edit',	(int)User::have_permit(ADMIN_ITEM));
		$display->add('browser_is_ie',	$this->browser_is_ie);
		$display->output('ajax_upload');
		//For ajax_upload form
        
		
		$this->beginForm(true);
		$display->add('max_image_page',$this->max_image_page);
		$display->add('images_per_page',$this->images_per_page);
		$display->add('post_item_images',$this->item_images);
		
		$display->add('jsImages',json_encode($this->jsImages));
		
		$display->add('first_combo',(int)Url::get('first_combo'));
		$display->add('second_combo',(int)Url::get('second_combo'));
		
		//$display->add('category_tree',json_encode(AZLib::getCategoriesTree(0,true)));
		$display->add('category_tree',json_encode(AZLib::getCategoriesTree(true)));
		
		$display->add('currency_tree',json_encode(CGlobal::$currency));
		
		$display->add('az_filters',json_encode(CGlobal::$filters));
		
		$display->add('image_path','http://'.IMAGE_PATH);
		$display->add('img_cur_server',IMAGE_SERVER_NO);
		$display->add('img_server',json_encode(CGlobal::$img_server));
		
		$display->add('no_img',	$this->no_image);
		$display->add('multi_upload',User::have_permit(ADMIN_ITEM));
        
		$display->add('post_img', $display->output('post_img',true));
		$display->add('currency_id_option',	AZLib::getOption(CGlobal::$currency,Url::get('currency_id',1)));
		
		$display->add('msg',$this->showFormErrorMessages(1));		
		$display->add('mode',"ĐĂNG");
		$display->add('sku',Url::get('sku'));
		$display->add('name',stripslashes(Url::get('name')));
		$display->add('offer',stripslashes(Url::get('offer')));
		
		$display->add('brief',stripslashes(Url::get('brief')));
		$display->add('item_description',stripslashes(Url::get('item_description')));
		$display->add('price',number_format(Url::cdouble(Url::get('price')),0,',','.'));			
		$display->add('price',number_format(Url::cdouble(Url::get('price')),0,',','.'));
		$display->add('price_out',	number_format(Url::cdouble(Url::get('price_out')),0,',','.'));
		
		$display->add('quantity',	number_format(Url::cdouble(Url::get('quantity')),0,',','.'));
		$display->add('item_order',	(int)Url::get('item_order'));
		$display->add('made_in',	Url::get('made_in'));
		$display->add('warranty',	Url::get('warranty'));

		$display->add('add_for_user',User::have_permit(ADMIN_ITEM));
		$display->output('post_sale');
					
		$this->endForm();	
	}
	
	function on_submit()
	{
		AZLib::getCats();
		$sku  		= AZLib::trimSpace(str_replace("\n"," ",Url::get('sku')));
		
		###############################################################################################
		$name   	= AZLib::trimSpace(str_replace("\n"," ",Url::get('name')));
		
		mb_internal_encoding("UTF-8");
		$name 		= mb_strtoupper(mb_substr($name,0,1)).mb_substr($name,1);
		###############################################################################################
		
		###############################################################################################
		
		$offer   	= AZLib::trimSpace(str_replace("\n"," ",Url::get('offer')));
		
		mb_internal_encoding("UTF-8");
		$offer 		= mb_strtoupper(mb_substr($offer,0,1)).mb_substr($offer,1);
		###############################################################################################
		
		###############################################################################################
		
		$list_brief = AZLib::trimSpace(str_replace("\n"," ",Url::get('list_brief')));
		
		mb_internal_encoding("UTF-8");
		$list_brief 		= mb_strtoupper(mb_substr($list_brief,0,1)).mb_substr($list_brief,1);
		###############################################################################################
		
		
		###############################################################################################
		
		//$item_description 	= AZLib::getParam('item_description');
		$item_description 	= Url::get('item_description');
		$brief 				= Url::get('brief');
		
		if(get_magic_quotes_gpc()){
			$item_description  	= stripslashes($item_description);
			$brief  			= stripslashes($brief);
		}
		
		require_once ROOT_PATH.'includes/htmLawed.php';
		
		$config = array(
			'safe'=>1, // Dangerous elements and attributes thus not allowed
			'elements'=>'*', // All except table-related are OK
			'deny_attribute'=>'class, id' // None of the allowed elements can have these attributes
		);
		
		$spec = 'a = title, href;'; // The 'a' element can have only these attributes

		$item_description = htmLawed($item_description, $config, $spec);
		$item_description = AZLib::clean_value($item_description);

        $brief 				= htmLawed($brief, $config, $spec);
		$brief 				= AZLib::clean_value($brief);
		###############################################################################################
		
		
		$category_id =0;
		$level_1_catid = 0;
		
		$first_combo		= (int)Url::get('first_combo');
		$second_combo		= (int)Url::get('second_combo');
		$price				= Url::cdouble(Url::get('price',0));				
		$price_out			= Url::cdouble(Url::get('price_out',0));
		$currency_id		= (int)Url::get('currency_id',1);
		
		$quantity			= Url::cdouble(Url::get('quantity',0));
		
		if($quantity<0){
			$quantity = 0;
		}
		
		$item_order			= (int)Url::get('item_order');
		$made_in			= Url::get('made_in');
		$warranty			= Url::get('warranty');
		
		if(!isset(CGlobal::$currency[$currency_id])){
			$currency_id=1;
		}
		
		$item_category=false;
		
		if($first_combo && $second_combo){//Nếu chọn danh mục cấp 2
			$category_id 		 = $second_combo;
			$level_1_catid = $first_combo;
			$level_2_catid = $second_combo;
			
			if(isset(CGlobal::$allCategories[$category_id])){//Kiểm tra sự tồn tai của danh mục
				$item_category=CGlobal::$allCategories[$category_id];
				
				//Nếu danh mục của sản phẩm là danh mục cấp 1 và có danh mục con => chọn lại
				if((isset(CGlobal::$subCategories[$category_id]) && CGlobal::$subCategories[$category_id] && $item_category['parent_id']==0) ||$item_category['parent_id']!=$first_combo){
					$this->setFormError('category_id','Hãy chọn lại <b>Chủng loại</b> cho sản phẩm!');
				}
			}
		}
		elseif($first_combo){//Nếu chọn danh mục cấp 1
			$category_id 			= $first_combo;
			$level_1_catid 	= $first_combo;
			$level_2_catid 	= $first_combo;
			
			if(isset(CGlobal::$allCategories[$category_id])){ //Kiểm tra sự tồn tai của danh mục
				$item_category=CGlobal::$allCategories[$category_id];
				
				if(isset(CGlobal::$subCategories[$category_id]) && CGlobal::$subCategories[$category_id] && $item_category['parent_id']==0){//Nếu danh mục có danh mục con => Chọn lại!
					$this->setFormError('category_id','Hãy chọn lại <b>Chủng loại</b> cho sản phẩm!');
				}
				elseif($item_category['parent_id']!=0){//Nếu không fải là danh mục cấp 1
					$this->setFormError('category_id','Hãy chọn lại <b>Chủng loại</b> cho sản phẩm!');
				}
			}
		}
		
		if(!$item_category){
			$this->setFormError('category_id','Bạn chưa chọn <b>Danh mục</b> cho sản phẩm!');
		}
		
		$this->checkFormInput('Tên sản phẩm','name',$name,'str',true,'',5,255);
		
		$this->checkFormInput('Mô tả vắn tắt', 'brief',$brief,'str',false,'',15,500000);
		$this->checkFormInput('Mô tả sản phẩm','item_description',$item_description,'str',true,'',15,500000);
				
		//Check kiểm duyệt
		$status = 1;//Cho hiển thị
		
		$have_image_up = false;
		$form_img_server 	= Url::get('avatar_img_server',0);
		$this->img_url 		= Url::get('avatar_img_url','');
		
		foreach($this->item_images as $page=>$page_images){//trang
			foreach ($page_images as $image){
				if($image['img_new_id']){
					$have_image_up = true;
					break;
				}	
			}
		}
		
		if(!$this->errNum)
		{
            $item_array = array(
                'category_id'			=>$category_id,
                'level_1_catid'	=>$level_1_catid,
                'level_2_catid'	=>$level_2_catid,
                'currency_id'			=>$currency_id,
                'quantity'				=>$quantity,
                'item_order'			=>$item_order,
                'made_in'				=>$made_in,
                'warranty'				=>$warranty,
                'price'					=>$price,
                'price_out'				=>$price_out,
                'sku'					=>$sku,
                'name'					=>$name,
                'offer'					=>$offer,
                'list_brief'			=>$list_brief,
                'brief'					=>$brief,
                'description'			=>$item_description,
                'status'				=>$status,
                'created_time'			=>TIME_NOW,
                'user_id'				=>User::id(),
                'user_name'				=>User::user_name(),
                'modify_time'			=>TIME_NOW,
                'modify_user_name'		=>User::user_name(),
                'img_server'			=>	$form_img_server,
                'have_image'			=>(int)(bool)$this->img_url,
                'img_url'				=>$this->img_url,
                );

			$id =DB::insert('item',	$item_array);
			
			if(!$id){
				$this->setFormError('',"Không đăng được Sản phẩm! Mời bạn thử lại!");
			}
			
			$image_err=false;
			$i_server			=0;
			$img_url		='';
			$item_images			=array();
			$item_insert_temp_images=array();
			$item_insert_images		=array();
			$item_update_images		=array();
			$img_ids='';
			
			foreach($this->item_images as $page=>$page_images){//trang
				foreach ($page_images as $image){
					if($image['img_new_id']){
						$img=array();
						$img_ids				   .=($img_ids?',':'').$image['img_new_id'];
						
						$img['item_id']				=$id;
						$img['title']				=($image['title'] && $image['title']!='Ghi chú ảnh' && !AZLib::checkBadWord($image['title']))?addslashes($image['title']):'';
						$img['position']			=$image['stt'];
						$img['img_server']			=$image['img_server'];
						$img['img_url']	= '';
						$img['root_id']				=0;
						$img['time']				=TIME_NOW;
						$img['user_id']				=User::id();
						$img['user_name']			=User::user_name();
						
						if(!isset($item_images[$image['img_new_id']])){	
							$item_images[$image['img_new_id']]=$img;
						}
						else{
							$img['root_id']=$image['img_new_id'];
							$item_insert_temp_images[$image['img_new_id']]=$img;//Đúp bản ghi trong trường hợp 1 ảnh được chọn tại nhiều vị trí
						}
					}
				}
			}			
			
			if($img_ids)
			{
				$re=DB::query('SELECT id, item_id, user_id, img_server, img_url,root_id, time FROM item_image WHERE id IN('.$img_ids.')');
				
				if($re)
				{
					$pos=0;
					while ($img=mysql_fetch_assoc($re))
					{
						if(isset($item_insert_temp_images[$img['id']])){
							$item_insert_temp_images[$img['id']]['img_server']		= $img['img_server'];
							$item_insert_temp_images[$img['id']]['img_url']			= $img['img_url'];
							$item_insert_temp_images[$img['id']]['root_id']			= $img['id'];
							$item_insert_temp_images[$img['id']]['time']			= $img['time'];
							$item_insert_images[]									= $item_insert_temp_images[$img['id']];
						}
						
						$item_images[$img['id']]['time']					= $img['time'];
						$item_images[$img['id']]['img_server']				= $img['img_server'];
						$item_images[$img['id']]['img_url']					= $img['img_url'];
						
						if($img['item_id']){//Đã có item_id rồi, đúp bản ghi
							$image=$item_images[$img['id']];
							
							if($img['root_id'])
								$image['root_id']=$img['root_id'];
							else 
								$image['root_id']=$img['id'];
							
							$item_insert_images[]=$image;
						}
						else{//Chưa có item_id, cập nhật
							$img['item_id']=$id;


							$item_update_images[$img['id']]=$item_images[$img['id']];
						}
						
						if($img_url=='' || $pos==0 || $item_images[$img['id']]['position']<=$pos){
							$pos			=$item_images[$img['id']]['position'];
							$i_server		= $img['img_server'];
							$img_url		=$img['img_url'];
						}
					}
				}
			}
			
			if($item_insert_images)
			{
				$inser_sql='';
				
				foreach ($item_insert_images as $item_image)
				{
					$inser_sql.=($inser_sql?",":"")."
						('".addslashes($item_image['title'])."',
						'".$item_image['position']."','".$item_image['item_id']."',".$item_image['img_server'].",'".$item_image['img_url']."','".$item_image['root_id']."',
						'".$item_image['time']."','".$item_image['user_id']."','".$item_image['user_name']."')";
				}
				
				$inser_sql="INSERT INTO `item_image` (`title`,`position`,`item_id`,`img_server`,`img_url`,`root_id`,`time`,`user_id`,`user_name`) 
							VALUES ".$inser_sql;
				DB::query($inser_sql);
			}
			
			if($item_update_images){
				foreach ($item_update_images as $img_id=>$item_image){
					if(!DB::update('item_image',$item_image,'id='.$img_id)){
						$image_err=true;
					}
				}
			}						
			
			#Filters
			##############################################################################
			
			$item_array = array(
								'filter_search' => $filter_search,
								'filter_ids' 	=> $filter_ids
								);
			
			if($this->img_url == '' && $img_url !='' )
			{
				$item_array['img_server'] 	= $i_server;
				$item_array['img_url'] 		= $img_url;
				$item_array['have_image'] 	= 1;
			}
			elseif($item_have_image){
				$item_array['have_image'] 	= 1;
			}
			
			$item_array['filter_search'] 	= $filter_search;
			$item_array['filter_ids'] 		= $filter_ids;
			
			
			if($this->img_url == '' && $img_url !='' )
			{
				$item_array['img_server'] 	= $i_server;
				$item_array['img_url'] 		= $img_url;
				$item_array['have_image'] 	= 1;
			}
			elseif($item_insert_images || $item_update_images){//tuannk 2010.07.26
				$item_array['have_image'] 	= 1;
			}
			
			DB::update('item',$item_array,'id='.$id);
			
			if(Url::get('ref'))
				Url::redirect("manage_item");
			else
				Url::redirect("item_detail",array("id"=>$id));
		}
	}				
}
?>